home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / distutils / command / build_ext.py < prev    next >
Encoding:
Python Source  |  2000-08-13  |  22.6 KB  |  576 lines

  1. """distutils.command.build_ext
  2.  
  3. Implements the Distutils 'build_ext' command, for building extension
  4. modules (currently limited to C extensions, should accommodate C++
  5. extensions ASAP)."""
  6.  
  7. # created 1999/08/09, Greg Ward
  8.  
  9. __revision__ = "$Id: build_ext.py,v 1.60 2000/08/13 00:42:35 gward Exp $"
  10.  
  11. import sys, os, string, re
  12. from types import *
  13. from distutils.core import Command
  14. from distutils.errors import *
  15. from distutils.sysconfig import customize_compiler
  16. from distutils.dep_util import newer_group
  17. from distutils.extension import Extension
  18.  
  19. # An extension name is just a dot-separated list of Python NAMEs (ie.
  20. # the same as a fully-qualified module name).
  21. extension_name_re = re.compile \
  22.     (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
  23.  
  24.  
  25. def show_compilers ():
  26.     from distutils.ccompiler import show_compilers
  27.     show_compilers()
  28.  
  29.  
  30. class build_ext (Command):
  31.     
  32.     description = "build C/C++ extensions (compile/link to build directory)"
  33.  
  34.     # XXX thoughts on how to deal with complex command-line options like
  35.     # these, i.e. how to make it so fancy_getopt can suck them off the
  36.     # command line and make it look like setup.py defined the appropriate
  37.     # lists of tuples of what-have-you.
  38.     #   - each command needs a callback to process its command-line options
  39.     #   - Command.__init__() needs access to its share of the whole
  40.     #     command line (must ultimately come from
  41.     #     Distribution.parse_command_line())
  42.     #   - it then calls the current command class' option-parsing
  43.     #     callback to deal with weird options like -D, which have to
  44.     #     parse the option text and churn out some custom data
  45.     #     structure
  46.     #   - that data structure (in this case, a list of 2-tuples)
  47.     #     will then be present in the command object by the time
  48.     #     we get to finalize_options() (i.e. the constructor
  49.     #     takes care of both command-line and client options
  50.     #     in between initialize_options() and finalize_options())
  51.  
  52.     user_options = [
  53.         ('build-lib=', 'b',
  54.          "directory for compiled extension modules"),
  55.         ('build-temp=', 't',
  56.          "directory for temporary files (build by-products)"),
  57.         ('inplace', 'i',
  58.          "ignore build-lib and put compiled extensions into the source" +
  59.          "directory alongside your pure Python modules"),
  60.         ('include-dirs=', 'I',
  61.          "list of directories to search for header files"),
  62.         ('define=', 'D',
  63.          "C preprocessor macros to define"),
  64.         ('undef=', 'U',
  65.          "C preprocessor macros to undefine"),
  66.         ('libraries=', 'l',
  67.          "external C libraries to link with"),
  68.         ('library-dirs=', 'L',
  69.          "directories to search for external C libraries"),
  70.         ('rpath=', 'R',
  71.          "directories to search for shared C libraries at runtime"),
  72.         ('link-objects=', 'O',
  73.          "extra explicit link objects to include in the link"),
  74.         ('debug', 'g',
  75.          "compile/link with debugging information"),
  76.         ('force', 'f',
  77.          "forcibly build everything (ignore file timestamps)"),
  78.         ('compiler=', 'c',
  79.          "specify the compiler type"),
  80.         ('swig-cpp', None,
  81.          "make SWIG create C++ files (default is C)"),
  82.         ]
  83.  
  84.     help_options = [
  85.         ('help-compiler', None,
  86.          "list available compilers", show_compilers),
  87.         ]
  88.  
  89.     def initialize_options (self):
  90.         self.extensions = None
  91.         self.build_lib = None
  92.         self.build_temp = None
  93.         self.inplace = 0
  94.         self.package = None
  95.  
  96.         self.include_dirs = None
  97.         self.define = None
  98.         self.undef = None
  99.         self.libraries = None
  100.         self.library_dirs = None
  101.         self.rpath = None
  102.         self.link_objects = None
  103.         self.debug = None
  104.         self.force = None
  105.         self.compiler = None
  106.         self.swig_cpp = None
  107.  
  108.  
  109.     def finalize_options (self):
  110.         from distutils import sysconfig
  111.  
  112.         self.set_undefined_options ('build',
  113.                                     ('build_lib', 'build_lib'),
  114.                                     ('build_temp', 'build_temp'),
  115.                                     ('compiler', 'compiler'),
  116.                                     ('debug', 'debug'),
  117.                                     ('force', 'force'))
  118.  
  119.         if self.package is None:
  120.             self.package = self.distribution.ext_package
  121.  
  122.         self.extensions = self.distribution.ext_modules
  123.         
  124.  
  125.         # Make sure Python's include directories (for Python.h, config.h,
  126.         # etc.) are in the include search path.
  127.         py_include = sysconfig.get_python_inc()
  128.         plat_py_include = sysconfig.get_python_inc(plat_specific=1)
  129.         if self.include_dirs is None:
  130.             self.include_dirs = self.distribution.include_dirs or []
  131.         if type (self.include_dirs) is StringType:
  132.             self.include_dirs = string.split (self.include_dirs,
  133.                                               os.pathsep)
  134.  
  135.         # Put the Python "system" include dir at the end, so that
  136.         # any local include dirs take precedence.
  137.         self.include_dirs.append (py_include)
  138.         if plat_py_include != py_include:
  139.             self.include_dirs.append (plat_py_include)
  140.  
  141.         if type (self.libraries) is StringType:
  142.             self.libraries = [self.libraries]
  143.  
  144.         # Life is easier if we're not forever checking for None, so
  145.         # simplify these options to empty lists if unset
  146.         if self.libraries is None:
  147.             self.libraries = []
  148.         if self.library_dirs is None:
  149.             self.library_dirs = []
  150.         if self.rpath is None:
  151.             self.rpath = []
  152.  
  153.         # for extensions under windows use different directories
  154.         # for Release and Debug builds.
  155.         # also Python's library directory must be appended to library_dirs
  156.         if os.name == 'nt':
  157.             self.library_dirs.append (os.path.join(sys.exec_prefix, 'libs'))
  158.             self.implib_dir = self.build_temp
  159.             if self.debug:
  160.                 self.build_temp = os.path.join (self.build_temp, "Debug")
  161.             else:
  162.                 self.build_temp = os.path.join (self.build_temp, "Release")
  163.     # finalize_options ()
  164.     
  165.  
  166.     def run (self):
  167.  
  168.         from distutils.ccompiler import new_compiler
  169.  
  170.         # 'self.extensions', as supplied by setup.py, is a list of
  171.         # Extension instances.  See the documentation for Extension (in
  172.         # distutils.extension) for details.
  173.         # 
  174.         # For backwards compatibility with Distutils 0.8.2 and earlier, we
  175.         # also allow the 'extensions' list to be a list of tuples:
  176.         #    (ext_name, build_info)
  177.         # where build_info is a dictionary containing everything that
  178.         # Extension instances do except the name, with a few things being
  179.         # differently named.  We convert these 2-tuples to Extension
  180.         # instances as needed.
  181.  
  182.         if not self.extensions:
  183.             return
  184.  
  185.         # If we were asked to build any C/C++ libraries, make sure that the
  186.         # directory where we put them is in the library search path for
  187.         # linking extensions.
  188.         if self.distribution.has_c_libraries():
  189.             build_clib = self.get_finalized_command ('build_clib')
  190.             self.libraries.extend (build_clib.get_library_names() or [])
  191.             self.library_dirs.append (build_clib.build_clib)
  192.  
  193.         # Setup the CCompiler object that we'll use to do all the
  194.         # compiling and linking
  195.         self.compiler = new_compiler (compiler=self.compiler,
  196.                                       verbose=self.verbose,
  197.                                       dry_run=self.dry_run,
  198.                                       force=self.force)
  199.         customize_compiler(self.compiler)
  200.  
  201.         # And make sure that any compile/link-related options (which might
  202.         # come from the command-line or from the setup script) are set in
  203.         # that CCompiler object -- that way, they automatically apply to
  204.         # all compiling and linking done here.
  205.         if self.include_dirs is not None:
  206.             self.compiler.set_include_dirs (self.include_dirs)
  207.         if self.define is not None:
  208.             # 'define' option is a list of (name,value) tuples
  209.             for (name,value) in self.define:
  210.                 self.compiler.define_macro (name, value)
  211.         if self.undef is not None:
  212.             for macro in self.undef:
  213.                 self.compiler.undefine_macro (macro)
  214.         if self.libraries is not None:
  215.             self.compiler.set_libraries (self.libraries)
  216.         if self.library_dirs is not None:
  217.             self.compiler.set_library_dirs (self.library_dirs)
  218.         if self.rpath is not None:
  219.             self.compiler.set_runtime_library_dirs (self.rpath)
  220.         if self.link_objects is not None:
  221.             self.compiler.set_link_objects (self.link_objects)
  222.  
  223.         # Now actually compile and link everything.
  224.         self.build_extensions ()
  225.  
  226.     # run ()
  227.  
  228.  
  229.     def check_extensions_list (self, extensions):
  230.         """Ensure that the list of extensions (presumably provided as a
  231.         command option 'extensions') is valid, i.e. it is a list of
  232.         Extension objects.  We also support the old-style list of 2-tuples,
  233.         where the tuples are (ext_name, build_info), which are converted to
  234.         Extension instances here.
  235.  
  236.         Raise DistutilsSetupError if the structure is invalid anywhere;
  237.         just returns otherwise.
  238.         """
  239.         if type(extensions) is not ListType:
  240.             raise DistutilsSetupError, \
  241.                   "'ext_modules' option must be a list of Extension instances"
  242.         
  243.         for i in range(len(extensions)):
  244.             ext = extensions[i]
  245.             if isinstance(ext, Extension):
  246.                 continue                # OK! (assume type-checking done
  247.                                         # by Extension constructor)
  248.  
  249.             (ext_name, build_info) = ext
  250.             self.warn(("old-style (ext_name, build_info) tuple found in "
  251.                        "ext_modules for extension '%s'" 
  252.                        "-- please convert to Extension instance" % ext_name))
  253.             if type(ext) is not TupleType and len(ext) != 2:
  254.                 raise DistutilsSetupError, \
  255.                       ("each element of 'ext_modules' option must be an "
  256.                        "Extension instance or 2-tuple")
  257.  
  258.             if not (type(ext_name) is StringType and
  259.                     extension_name_re.match(ext_name)):
  260.                 raise DistutilsSetupError, \
  261.                       ("first element of each tuple in 'ext_modules' "
  262.                        "must be the extension name (a string)")
  263.  
  264.             if type(build_info) is not DictionaryType:
  265.                 raise DistutilsSetupError, \
  266.                       ("second element of each tuple in 'ext_modules' "
  267.                        "must be a dictionary (build info)")
  268.  
  269.             # OK, the (ext_name, build_info) dict is type-safe: convert it
  270.             # to an Extension instance.
  271.             ext = Extension(ext_name, build_info['sources'])
  272.  
  273.             # Easy stuff: one-to-one mapping from dict elements to
  274.             # instance attributes.
  275.             for key in ('include_dirs',
  276.                         'library_dirs',
  277.                         'libraries',
  278.                         'extra_objects',
  279.                         'extra_compile_args',
  280.                         'extra_link_args'):
  281.                 setattr(ext, key, build_info.get(key))
  282.  
  283.             # Medium-easy stuff: same syntax/semantics, different names.
  284.             ext.runtime_library_dirs = build_info.get('rpath')
  285.             if build_info.has_key('def_file'):
  286.                 self.warn("'def_file' element of build info dict "
  287.                           "no longer supported")
  288.  
  289.             # Non-trivial stuff: 'macros' split into 'define_macros'
  290.             # and 'undef_macros'.
  291.             macros = build_info.get('macros')
  292.             if macros:
  293.                 ext.define_macros = []
  294.                 ext.undef_macros = []
  295.                 for macro in macros:
  296.                     if not (type(macro) is TupleType and
  297.                             1 <= len(macro) <= 2):
  298.                         raise DistutilsSetupError, \
  299.                               ("'macros' element of build info dict "
  300.                                "must be 1- or 2-tuple")
  301.                     if len(macro) == 1:
  302.                         ext.undef_macros.append(macro[0])
  303.                     elif len(macro) == 2:
  304.                         ext.define_macros.append(macro)
  305.  
  306.             extensions[i] = ext
  307.  
  308.         # for extensions
  309.  
  310.     # check_extensions_list ()
  311.  
  312.  
  313.     def get_source_files (self):
  314.         self.check_extensions_list(self.extensions)
  315.         filenames = []
  316.  
  317.         # Wouldn't it be neat if we knew the names of header files too...
  318.         for ext in self.extensions:
  319.             filenames.extend (ext.sources)
  320.  
  321.         return filenames
  322.  
  323.  
  324.     def get_outputs (self):
  325.  
  326.         # Sanity check the 'extensions' list -- can't assume this is being
  327.         # done in the same run as a 'build_extensions()' call (in fact, we
  328.         # can probably assume that it *isn't*!).
  329.         self.check_extensions_list (self.extensions)
  330.  
  331.         # And build the list of output (built) filenames.  Note that this
  332.         # ignores the 'inplace' flag, and assumes everything goes in the
  333.         # "build" tree.
  334.         outputs = []
  335.         for ext in self.extensions:
  336.             fullname = self.get_ext_fullname (ext.name)
  337.             outputs.append (os.path.join (self.build_lib,
  338.                                           self.get_ext_filename(fullname)))
  339.         return outputs
  340.  
  341.     # get_outputs ()
  342.  
  343.  
  344.     def build_extensions (self):
  345.  
  346.         # First, sanity-check the 'extensions' list
  347.         self.check_extensions_list (self.extensions)
  348.  
  349.         for ext in self.extensions:
  350.             sources = ext.sources
  351.             if sources is None or type (sources) not in (ListType, TupleType):
  352.                 raise DistutilsSetupError, \
  353.                       ("in 'ext_modules' option (extension '%s'), " +
  354.                        "'sources' must be present and must be " +
  355.                        "a list of source filenames") % ext.name
  356.             sources = list (sources)
  357.  
  358.             fullname = self.get_ext_fullname (ext.name)
  359.             if self.inplace:
  360.                 # ignore build-lib -- put the compiled extension into
  361.                 # the source tree along with pure Python modules
  362.  
  363.                 modpath = string.split (fullname, '.')
  364.                 package = string.join (modpath[0:-1], '.')
  365.                 base = modpath[-1]
  366.  
  367.                 build_py = self.get_finalized_command ('build_py')
  368.                 package_dir = build_py.get_package_dir (package)
  369.                 ext_filename = os.path.join (package_dir,
  370.                                              self.get_ext_filename(base))
  371.             else:
  372.                 ext_filename = os.path.join (self.build_lib,
  373.                                              self.get_ext_filename(fullname))
  374.  
  375.             if not (self.force or newer_group(sources, ext_filename, 'newer')):
  376.                 self.announce ("skipping '%s' extension (up-to-date)" %
  377.                                ext.name)
  378.                 continue # 'for' loop over all extensions
  379.             else:
  380.                 self.announce ("building '%s' extension" % ext.name)
  381.  
  382.             # First, scan the sources for SWIG definition files (.i), run
  383.             # SWIG on 'em to create .c files, and modify the sources list
  384.             # accordingly.
  385.             sources = self.swig_sources(sources)
  386.  
  387.             # Next, compile the source code to object files.
  388.  
  389.             # XXX not honouring 'define_macros' or 'undef_macros' -- the
  390.             # CCompiler API needs to change to accommodate this, and I
  391.             # want to do one thing at a time!
  392.  
  393.             # Two possible sources for extra compiler arguments:
  394.             #   - 'extra_compile_args' in Extension object
  395.             #   - CFLAGS environment variable (not particularly
  396.             #     elegant, but people seem to expect it and I
  397.             #     guess it's useful)
  398.             # The environment variable should take precedence, and
  399.             # any sensible compiler will give precedence to later
  400.             # command line args.  Hence we combine them in order:
  401.             extra_args = ext.extra_compile_args or []
  402.  
  403.             # XXX and if we support CFLAGS, why not CC (compiler
  404.             # executable), CPPFLAGS (pre-processor options), and LDFLAGS
  405.             # (linker options) too?
  406.             # XXX should we use shlex to properly parse CFLAGS?
  407.  
  408.             if os.environ.has_key('CFLAGS'):
  409.                 extra_args.extend(string.split(os.environ['CFLAGS']))
  410.                 
  411.             objects = self.compiler.compile (sources,
  412.                                              output_dir=self.build_temp,
  413.                                              #macros=macros,
  414.                                              include_dirs=ext.include_dirs,
  415.                                              debug=self.debug,
  416.                                              extra_postargs=extra_args)
  417.  
  418.             # Now link the object files together into a "shared object" --
  419.             # of course, first we have to figure out all the other things
  420.             # that go into the mix.
  421.             if ext.extra_objects:
  422.                 objects.extend (ext.extra_objects)
  423.             extra_args = ext.extra_link_args or []
  424.  
  425.  
  426.             self.compiler.link_shared_object (
  427.                 objects, ext_filename, 
  428.                 libraries=self.get_libraries(ext),
  429.                 library_dirs=ext.library_dirs,
  430.                 runtime_library_dirs=ext.runtime_library_dirs,
  431.                 extra_postargs=extra_args,
  432.                 export_symbols=self.get_export_symbols(ext), 
  433.                 debug=self.debug,
  434.                 build_temp=self.build_temp)
  435.  
  436.     # build_extensions ()
  437.  
  438.  
  439.     def swig_sources (self, sources):
  440.  
  441.         """Walk the list of source files in 'sources', looking for SWIG
  442.         interface (.i) files.  Run SWIG on all that are found, and
  443.         return a modified 'sources' list with SWIG source files replaced
  444.         by the generated C (or C++) files.
  445.         """
  446.  
  447.         new_sources = []
  448.         swig_sources = []
  449.         swig_targets = {}
  450.  
  451.         # XXX this drops generated C/C++ files into the source tree, which
  452.         # is fine for developers who want to distribute the generated
  453.         # source -- but there should be an option to put SWIG output in
  454.         # the temp dir.
  455.  
  456.         if self.swig_cpp:
  457.             target_ext = '.cpp'
  458.         else:
  459.             target_ext = '.c'
  460.  
  461.         for source in sources:
  462.             (base, ext) = os.path.splitext(source)
  463.             if ext == ".i":             # SWIG interface file
  464.                 new_sources.append(base + target_ext)
  465.                 swig_sources.append(source)
  466.                 swig_targets[source] = new_sources[-1]
  467.             else:
  468.                 new_sources.append(source)
  469.  
  470.         if not swig_sources:
  471.             return new_sources
  472.  
  473.         swig = self.find_swig()
  474.         swig_cmd = [swig, "-python", "-dnone", "-ISWIG"]
  475.         if self.swig_cpp:
  476.             swig_cmd.append ("-c++")
  477.  
  478.         for source in swig_sources:
  479.             target = swig_targets[source]
  480.             self.announce ("swigging %s to %s" % (source, target))
  481.             self.spawn(swig_cmd + ["-o", target, source])
  482.  
  483.         return new_sources
  484.  
  485.     # swig_sources ()
  486.  
  487.     def find_swig (self):
  488.         """Return the name of the SWIG executable.  On Unix, this is
  489.         just "swig" -- it should be in the PATH.  Tries a bit harder on
  490.         Windows.
  491.         """
  492.  
  493.         if os.name == "posix":
  494.             return "swig"
  495.         elif os.name == "nt":
  496.  
  497.             # Look for SWIG in its standard installation directory on
  498.             # Windows (or so I presume!).  If we find it there, great;
  499.             # if not, act like Unix and assume it's in the PATH.
  500.             for vers in ("1.3", "1.2", "1.1"):
  501.                 fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  502.                 if os.path.isfile (fn):
  503.                     return fn
  504.             else:
  505.                 return "swig.exe"
  506.  
  507.         else:
  508.             raise DistutilsPlatformError, \
  509.                   ("I don't know how to find (much less run) SWIG "
  510.                    "on platform '%s'") % os.name
  511.  
  512.     # find_swig ()
  513.     
  514.     # -- Name generators -----------------------------------------------
  515.     # (extension names, filenames, whatever)
  516.  
  517.     def get_ext_fullname (self, ext_name):
  518.         if self.package is None:
  519.             return ext_name
  520.         else:
  521.             return self.package + '.' + ext_name
  522.  
  523.     def get_ext_filename (self, ext_name):
  524.         """Convert the name of an extension (eg. "foo.bar") into the name
  525.         of the file from which it will be loaded (eg. "foo/bar.so", or
  526.         "foo\bar.pyd").
  527.         """
  528.  
  529.         from distutils import sysconfig
  530.         ext_path = string.split (ext_name, '.')
  531.         # extensions in debug_mode are named 'module_d.pyd' under windows
  532.         if os.name == 'nt' and self.debug:
  533.             return apply (os.path.join, ext_path) + '_d' + sysconfig.SO
  534.         return apply (os.path.join, ext_path) + sysconfig.SO
  535.  
  536.     def get_ext_libname (self, ext_name):
  537.         # create a filename for the (unneeded) lib-file.
  538.         # extensions in debug_mode are named 'module_d.pyd' under windows
  539.         ext_path = string.split (ext_name, '.')
  540.         if os.name == 'nt' and self.debug:
  541.             return apply (os.path.join, ext_path) + '_d.lib'
  542.         return apply (os.path.join, ext_path) + '.lib'
  543.  
  544.  
  545.     def get_export_symbols (self, ext):
  546.         """Return the list of symbols that a shared extension has to
  547.         export.  This either uses 'ext.export_symbols' or, if it's not
  548.         provided, "init" + module_name.  Only relevant on Windows, where
  549.         the .pyd file (DLL) must export the module "init" function.
  550.         """
  551.  
  552.         initfunc_name = "init" + string.split(ext.name,'.')[-1]
  553.         if initfunc_name not in ext.export_symbols:
  554.             ext.export_symbols.append(initfunc_name)
  555.         return ext.export_symbols
  556.  
  557.     def get_libraries (self, ext):
  558.         """Return the list of libraries to link against when building a
  559.         shared extension.  On most platforms, this is just 'ext.libraries';
  560.         on Windows, we add the Python library (eg. python20.dll).
  561.         """
  562.         # The python library is always needed on Windows.  For MSVC, this
  563.         # is redundant, since the library is mentioned in a pragma in
  564.         # config.h that MSVC groks.  The other Windows compilers all seem
  565.         # to need it mentioned explicitly, though, so that's what we do.
  566.         if sys.platform == "win32": 
  567.             pythonlib = ("python%d%d" %
  568.                  (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  569.             # don't extend ext.libraries, it may be shared with other
  570.             # extensions, it is a reference to the original list
  571.             return ext.libraries + [pythonlib]
  572.         else:
  573.             return ext.libraries
  574.  
  575. # class build_ext
  576.